<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <link href="${gPath}/styles/dpl-min.css" rel="stylesheet" />
    <link href="${gPath}/styles/bui-min.css" rel="stylesheet" />
    <link href="${gPath}/styles/main.css" rel="stylesheet" />
</head>
<body>
<!--列表页-->
<div class="container">
    <form id="searchForm" class="form-panel">
        <div class="panel-content row">
            <div class="row" style="margin: 4px 4px;float: left;">
                <span>
                    <label>账号：</label><input type="text" class="control-text" name="account.account"/>
                </span>
                <span>
                    <label>姓名：</label><input type="text" class="control-text" name="account.name"/>
                </span>
                <span>
                    <label>工号：</label><input type="text" class="control-text" name="account.job_no"/>
                </span>
            </div>
            <div class="row" style="margin: 4px 4px;float: left;">
                <span>
                    <label>&nbsp;部&nbsp;门：</label><input type="text" class="control-text" name="account.department"/>
                </span>
                <span>
                    <label>手机：</label><input type="text" class="control-text" name="account.mobile"/>
                </span>
                <span>
                    <label>状态：</label>
                    <select name="account.status">
                        <option value="">全部</option>
                        <option value="0">冻结</option>
                        <option value="1">生效</option>
                        <option value="2">离职</option>
                    </select>
                </span>
                <button type="button" id="btnSearch" class="button button-primary">搜索</button>
            </div>
        </div>
    </form>
    <div class="search-grid-container">
        <div id="grid"></div>
    </div>
</div>

<!--表单页-->
<div id="ModelFormDialog" style="display: none">
    <form id="ModelForm" class="form-horizontal">
        <div class="control-group">
            <label class="control-label">账号：</label>
            <div class="controls">
                <input data-rules="{required:true}" data-messages="{required:'账号不能为空'}" data-tip="{text:'请输入账号'}"   class="input-normal control-text" type="text" name="account.account"/>
            </div>
        </div>
        <div class="control-group" id="formPassword">
            <label class="control-label">密码：</label>
            <div class="controls">
                <input class="input-normal control-text" data-rules="{required:true}" data-messages="{required:'密码不能为空'}" data-tip="{text:'请输入密码'}" type="text" name="account.password"/>
            </div>
        </div>
        <div class="control-group">
            <label class="control-label">姓名：</label>
            <div class="controls">
                <input class="input-normal control-text" type="text" name="account.name" />
            </div>
        </div>
        <div class="control-group">
            <label class="control-label">角色：</label>
            <div class="controls" id="roleSelectDiv"></div>
        </div>
        <div class="control-group">
            <label class="control-label">工号：</label>
            <div class="controls">
                <input class="input-normal control-text" type="text" name="account.job_no" />
            </div>
        </div>
        <div class="control-group">
            <label class="control-label">公司：</label>
            <div class="controls">
                <select name="account.company_id">
                    <option value="0">苏州科贝尔实业有限公司</option>
                </select>
            </div>
        </div>
        <div class="control-group">
            <label class="control-label">部门：</label>
            <div class="controls">
                <input class="input-normal control-text" type="text" name="account.department" />
            </div>
        </div>
        <div class="control-group">
            <label class="control-label">手机：</label>
            <div class="controls">
                <input class="input-normal control-text" data-rules="{regexp:[/^1[3|4|5|8][0-9]\d{8}$/,'请输入正确的手机号码']}"  type="text" name="account.mobile" />
            </div>
        </div>
        <div class="control-group">
            <label class="control-label">邮箱：</label>
            <div class="controls">
                <input class="input-normal control-text" data-rules="{email:true}"  type="text" name="account.email" />
            </div>
        </div>
        <div class="control-group">
            <label class="control-label">状态：</label>
            <div class="controls">
                <select name="account.status">
                    <option value="1">生效</option>
                    <option value="0">冻结</option>
                    <option value="2">离职</option>
                </select>
            </div>
        </div>
        <div class="control-group">
            <label class="control-label">备注：</label>
            <div class="controls">
                <input class="input-normal control-text" type="text" name="account.remark" />
            </div>
        </div>
        <div class="row form-actions actions-bar">
            <div class="span13 offset3 ">
                <button type="submit" class="button button-primary">保存</button>
                <button type="reset" class="button">重置</button>
            </div>
        </div>
    </form>
</div>

<div id="importMemberModal" class="is-hide ">
    <div class="text-center">
        <h1 class="pull-left span18">导入成员</h1>
        <p class="span18" style="margin-top: 5%">首先下载好EXCEL表格，再填写，再导入。 </p>
        <a target="_blank" href="http://cy-clmp.qiniudn.com/clmp导入账号模板.xlsx" class="button">下载EXCEL表格模板</a>
        <hr>
    </div>
    <div class="text-center">
        <div id="J_Uploader"></div>
    </div>
    <div class="text-center importing" style="display: none;">
        <div class="tips tips-small tips-info span5 offset7">
            <span class="x-icon x-icon-small x-icon-info"><i class="icon icon-white icon-info"></i></span>
            <div class="tips-content">正在导入中，请稍后...</div>
        </div>
    </div>
</div>

<script type="text/javascript" src="${gPath}/scripts/jquery/jquery-1.8.1.min.js"></script>
<script type="text/javascript" src="${gPath}/scripts/bui.js"></script>
<script type="text/javascript" src="${gPath}/scripts/common/search.js"></script>
<script type="text/javascript">
var URI = "${gPath}/clmp/account", MODULE='account';
BUI.use(['common/search', 'bui/overlay', 'bui/form'], function (Search, Overlay, Form) {
    $.getJSON("${gPath}/item", {className: ["com.cy.model.Company"]}, function(result){
        var selectEle = $("select[name='account.company_id']");
        for (var i in result.companyItems){
            var d = result.companyItems[i];
            selectEle.append("<option value='"+ d.id +"'>"+ d.name +"</option>");
        }
    });

    var columns = [
        {dataIndex: 'company_id', visible: false},
        {title: '账号id', dataIndex: 'account_id', width: '5%'},
        {title: '账号', dataIndex: 'account', width: '10%'},
        {title: '姓名', dataIndex: 'name', width: '10%'},
        {title: '工号', dataIndex: 'job_no', width: '5%'},
        {title: '部门', dataIndex: 'department', width: '10%'},
        {title: '手机', dataIndex: 'mobile', width: '10%'},
        {title: '邮箱', dataIndex: 'email', width: '10%'},
        {title: '状态', dataIndex: 'status', width: '10%',renderer:function(value, obj){
            switch (value){
                case 0:return '冻结';
                case 1:return '在职';
                case 2:return '离职';
                default : return value;
            }
        }},
        {title: '公司', dataIndex: 'companyName', width: '10%',renderer:function(value, obj){
            return obj.company_id == 0 ? '苏州科贝尔实业有限公司' : value;
        }},
        {title: '创建时间', dataIndex: 'create_time', width: '10%'},
        {title: '备注', dataIndex: 'remark', width: '10%'},
        {title: '操作', dataIndex: '', width: '8%', renderer: function (value, obj) {
            var editStr = '<shiro:hasPermission name="/clmp/account/*:post"><span class="grid-command btn-edit" title="编辑">编辑</span></shiro:hasPermission>';
            var delStr = '<shiro:hasPermission name="/clmp/account/*:delete"><span class="grid-command btn-del" title="删除">删除</span></shiro:hasPermission>';
            return editStr + delStr;
    }}];
    var store = Search.createStore(URI, {totalProperty: 'total'});
    var gridCfg = Search.createGridCfg(columns, {
        tbar: {
            items: [
                <shiro:hasPermission name="/res/_webApi/excel/account">
                {
                    text: '<i class="icon-upload"></i>批量导入', btnCls: 'button button-small', handler: function () {
                        importMemberModal.show();
                    }
                },
                </shiro:hasPermission>
                <shiro:hasPermission name="/clmp/account:post">
                {
                    text: '<i class="icon-plus"></i>新建', btnCls: 'button button-small', handler: function () {
                        var accountField = modelFormObject.getField('account.account');
                        accountField.set('remote',{
                            url : '../clmp/account/get_checkAccountUnique',
                            dataType:'json',
                            callback : function(data){
                                return data.data == 1 ? "" : data.msg;
                            }
                        });
                        accountField.set('disabled', false);
                        modelFormObject.clearFields();
                        loadRoles();
                        modelFormObject.set('action', URI);
                        modelFormObject.set('method', "POST");
                        modelFormDialog.show();
                        $("#formPassword").show().removeAttr("disable");
                    }
                },
                </shiro:hasPermission>
                {
                <shiro:hasPermission name="/clmp/account/*:delete">
                    text: '<i class="icon-remove"></i>删除', btnCls: 'button button-small', handler: delFunction
                </shiro:hasPermission>
                }
        ]},
        emptyDataTpl : '<div style="padding: 20px" class="centered"><img src="${gPath}/img/nodata.png"><h2>好像还没有数据</h2></div>',
        plugins: [BUI.Grid.Plugins.CheckSelection]
    });

    var search = new Search({
        store: store,
        gridCfg: gridCfg
    });
    var grid = search.get('grid');

    //删除操作
    function delFunction() {
        var selections = grid.getSelection();
        delItems(selections);
    }

    function delItems(items) {
        var ids = [];
        BUI.each(items, function (item) {
            if(item.account_id == parent.account.account_id){
                BUI.Message.Alert('不能删除自己的账号');
                return false;
            }
            ids.push(item.account_id);
        });

        if (ids.length) {
            BUI.Message.Confirm('确认要删除选中的记录么？', function () {
                $.ajax({
                    url: URI + "/" + ids.join("-"),
                    dataType: 'json',
                    type: 'DELETE',
                    data: {ids: ids},
                    success: function (data) {
                        if (data.status == 1) {
                            BUI.Message.Alert('操作成功');
                            search.load();
                        } else {
                            BUI.Message.Alert('删除失败！');
                        }
                    }
                });
            }, 'question');
        }
    }

    //监听事件，删除一条记录
    grid.on('cellclick', function (ev) {
        var sender = $(ev.domTarget); //点击的Dom
        if (sender.hasClass('btn-del')) {
            delItems([ev.record]);
        } else if (sender.hasClass('btn-edit')) {
            $("#formPassword").hide().attr("disable",true);
            edit(ev.record);
        }
    });

    function edit(record) {
        modelFormObject.clearFields();
        loadRoles(record);
        modelFormObject.set('action', URI + "/" + record.account_id);
        modelFormObject.set('method', "POST");
        for (var name in record) {
            modelFormObject.setFieldValue(MODULE+'.' + name, record[name]);
        }
        modelFormObject.getField('account.account').set('disabled', true);
        modelFormDialog.show();
    }

    var modelFormDialog = new Overlay.Dialog({
        title: '账号',
        width: 600,
        height: 500,
        mask: false,
        buttons: [],
        contentId: 'ModelFormDialog'
    });
    modelFormDialog.on("hide", function(){
        modelFormObject.getField('account.account').removeAttr('remote');
        $("#roleSelectDiv").empty();
    });

    var importMemberModal = new Overlay.Dialog({
        title: '批量导入',
        width: 800,
        height: 400,
        mask: false,
        buttons: [],
        contentId: 'importMemberModal'
    });

    var modelFormObject = new Form.HForm({
        srcNode: '#ModelForm',
        submitType: 'ajax',
        callback: function (data) {
            if (data.status == 1) {
                BUI.Message.Alert('操作成功');
                modelFormDialog.hide();
                search.load();
            } else {
                BUI.Message.Alert('操作失败!' + data.msg);
            }
        }
    }).render();

    function loadRoles(record){
        $.getJSON(URI + "/getRoles", {"accountId": record ? record.account_id : null}, function(data){
            var roleSelectDiv = $("#roleSelectDiv");
            for (var i = 0; i < data.length; i++){
                roleSelectDiv.append("<input type='checkbox' name='roleIds' value='"+ data[i].id +"' "+ (data[i].checked ? "checked" : "") +"/>"+ data[i].name +"&emsp;");
                /*if (i % 3 == 0)
                    roleSelectDiv.append("<br/>");*/
            }
        });
    }

    //添加 名字为 moblie的校验规则
    Form.Rules.add({
        name : 'moblie',  //规则名称
        validator : function(value,baseValue,formatMsg){ //验证函数，验证值、基准值、格式化后的错误信息
            var regexp = new RegExp('^1[3|4|5|8][0-9]\\d{4,8}$');
            if(value && !regexp.test(value)){
                return formatMsg;
            }
        }
    });
    BUI.use('bui/uploader',function (Uploader) {
        var uploader = new Uploader.Uploader({
            render: '#J_Uploader',
            url: '${gPath}/res/_webApi/excel/account',
            queue: {
                resultTpl:{
                    'success': '<div class="success">成功导入</div>',
                    'error': '<div class="error"><span class="uploader-error">{msg}</span></div>'
                }
            },
            rules: {
                //文的类型
                ext: ['.xls,.xlsx,.xlsm','文件类型只能为{0}'],
                //上传的最大个数
                max: [5, '文件的最大个数不能超过{0}个'],
                //文件大小的最小值,这个单位是kb
                minSize: [1, '文件的大小不能小于{0}KB'],
                //文件大小的最大值,单位也是kb
                maxSize: [1024, '文件大小不能大于1M']
            },
            isSuccess: function(result){
                $(".importing").hide();
                if(result && result.code == 20001){
                    BUI.Message.Alert("成功导入"+result.count+'条数据;'+result.msg);
                    importMemberModal.hide();
                    search.load();
                    $(".action .bui-queue-item-del").target("click");
                    return true;
                }
                $(".action .bui-queue-item-del").target("click");
                BUI.Message.Alert("系统繁忙");
                return false;
            }
        }).render();

        uploader.on("start",function(e){
            $(".importing").show();
        })
    });
});
</script>
</body>
</html>